import Taro from "@tarojs/taro";
import {View} from "@tarojs/components";
import "./search-result.less";
import Api from "../../api/api";
import dayjs from "dayjs";
import Note from "../../commponents/note/note";
import Loadmore from "../../commponents/load-more/load-more";
import NavBar from "../../commponents/nav-bar/nav-bar";

export default class SearchResult extends Taro.Component {
  config = {
    onReachBottomDistance: 400
  };

  constructor() {
    super(...arguments);
    this.state = {
      docList: [],
      loadingMore: "",
      pageNo: 1,
      keyword: ""
    };
  }

  async componentWillMount() {
    const params = this.$router.params;
    this.getSearchResult(params.keyword, 1);
    this.setState({
      keyword: params.keyword
    });
  }

  async onReachBottom() {
    if (this.state.loadingMore === "noMore") {
      return;
    }
    this.getSearchResult(this.state.keyword, this.state.pageNo + 1);
  }

  async getSearchResult(keyword, pageNo) {
    this.setState({loadingMore: "loading"});
    let d = await Api.docList(keyword, 0, pageNo, 50);
    let res = d.data.data;

    let list = res.list;
    let docList = this.state.docList;
    list.forEach(v => {
      v.createdAt = dayjs(v.created_at).format("YYYY-MM-DD HH:mm");
      docList.push(v);
    });

    const loadingMore = res.hasNext ? "" : "noMore";
    this.setState({
      loadingMore: loadingMore,
      docList: docList,
      pageNo: pageNo
    });
  }

  render() {
    return (
      <View>
        <NavBar title='搜索结果'/>
        <View class="container">
          <View class="note-list">
            {this.state.docList.map((item, index) => {
              return <Note note={item} from="2" key={index}/>;
            })}
          </View>
          <Loadmore loadingMore={this.state.loadingMore}/>
        </View>
      </View>
    );
  }
}
